package com.jx.tool.xmlexcel.md054;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import com.jx.tool.utils.FileFinder;
import com.jx.tool.utils.XmlUtils;

public class XmlExcelMD054 {

	public static void main(String[] args) {
		FileFinder finder = new FileFinder(".xml");
		List<File> files = finder.find(new File("."));
		try {
			for (File file : files) {
				writeExcel(excelFile(file), readXml(file));
			}
		} catch (Exception e) {
			writeErrors(e);
		}
	}

	private static DT_MDM_Req readXml(File file) throws Exception {
		return XmlUtils.xmlToObject(file, DT_MDM_Req.class);
	}

	private static void writeExcel(File file, DT_MDM_Req req) throws Exception {
		List<DT_MD054> md054s = req.getXML_DATA().getMD054();
		WritableWorkbook book = Workbook.createWorkbook(file);
		WritableSheet sheet = book.createSheet("sheet1", 0);
		for (int i = 0; i < md054s.size(); i++) {
			DT_MD054 md054 = md054s.get(i);
			sheet.addCell(new Label(0, i, md054.getMATNR()));
			sheet.addCell(new Label(1, i, md054.getWERKS()));
		}
		book.write();
		book.close();
	}

	private static File excelFile(File xFile) {
		String xPath = xFile.getPath();
		int index = xPath.lastIndexOf(".xml");
		String ePath = xPath.substring(0, index) + ".xls";
		return new File(ePath);
	}

	private static void writeErrors(Exception exception) {
		try {
			FileOutputStream fos = new FileOutputStream(new File(
					"errors.txt"), true);
			PrintStream ps = new PrintStream(fos);
			exception.printStackTrace(ps);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
